const { buildRoot, root } = require("../config.json");
const fs = require("fs");
const { devPath, writeFile ,buildPath} = require("../app/util");
const vm = require("vm");
const nodeSass = require("node-sass");

const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
  })

let settingsData = { global: {}, pages_settings: [] };
let settingsScheme = { global_setting: [], pages_setting: [], blocks_setting: [] };

//缓存积木块配置信息
let blocksSetting = {};

let styleFileContent = "";

let javascriptFileContent = "";

//获取默认积木块配置
function getDefaultBlock() {
    const defaultDirPath = "./src/default/view/sections";
    fs.readdir(defaultDirPath, function (err, files) {
        files.forEach(function (file) {
            const content = JSON.parse(fs.readFileSync(defaultDirPath + "/" + file + "/index.json", "utf-8"));
            blocksSetting[file] = content.schema;
        });
    });
}

//设置全局配置
function getGlobal() {
    const global = JSON.parse(fs.readFileSync(devPath("/config/global.json"), "utf-8"));
    settingsScheme.global_setting = global;
    global.forEach((element) => {
        element.settings.forEach((setting) => {
            settingsData.global[setting.id] = setting.default;
        });
    });


}

/**
 * @description: 获取页面配置
 * @param {*}
 * @return {*}
 */
function getPage() {
    const pageContent = JSON.parse(fs.readFileSync(devPath("/config/page.json"), "utf-8"));
    pageContent.forEach((element,index) => {
        settingsData.pages_settings.push({
            route: element.route,
            route_handle: element.route_handle,
            sections: []
        });

        settingsScheme.pages_setting.push({
            name: element.name,
            route: element.route,
            max_block: element.max_block,
            route_handle: element.route_handle,
            sections: []
        });

        element.sections.forEach((setting) => {
            settingsData.pages_settings[index].sections.push({
                type: setting.type,
                route: element.route_handle,
                params: setting.params
            });
            settingsScheme.pages_setting[index].sections.push({
                type: setting.type,
                fixed: setting.fixed,
                name:blocksSetting[setting.type].name || {}
            });
        });
    });
}

/**
 * @description: 获取积木块配置
 * @param {*}
 * @return {*}
 */
function getblock() {
    const blockContent = JSON.parse(fs.readFileSync(devPath("/config/block.json"), "utf-8"));
    settingsScheme.blocks_setting = blockContent.map((blocks) => {
      blocks.sections = blocks.sections.map((block) => {
            if (blocksSetting[block]) {
                return {
                    name: blocksSetting[block].name,
                    type: "block",
                    icon: blocksSetting[block].icon,
                    routes: blocksSetting[block].routes || [],
                    id: block
                };
            } 

            return {
                type: "block",
                id: block
            };
        });
        return blocks
    });
}

/**
 * @description: 创建模版样式
 * @param {*}
 * @return {*}
 */
function createTemplateStyle(config){

    Object.keys(config.style.assets).forEach(key=>{
        const cssContent = nodeSass.renderSync({
            data: `\n/** template style start **/\n@import "${devPath(config.style.assets[key])}";\n/** template style start **/\n${styleFileContent}`
        }).css;
        writeFile( buildPath(`/assets/${root}_${key}.css`), cssContent);
    })
    
}

/**
 * @description: 创建layout模版
 * @param {*}
 * @return {*}
 */
 function createTemplateLayout(config){
     
    const links = []
    Object.keys(config.style.assets).forEach(key=>{
        links.push( `<link rel="stylesheet" type="text/css" href="{{ '${root}_${key}.css' | asset_abs_url }}">`)
    })

    const temp = fs.readFileSync("./config/template/theme.liquid", "utf-8");
    writeFile( buildPath(`/layout/theme.liquid`),  temp.replace("<!-- style -->", links.join("\n")));
   
}

/**
 * @description: 组合文件内容
 * @param {*} html 
 * @param {*} css
 * @param {*} javascript
 * @param {*} json
 * @return {*}
 */
function createLiquidBody(html, css, javascript, json) {
    let bodys = [];
    if (json.schema && css) {
        bodys.push(`{% stylesheet %}${css}{% endstylesheet %}`);
    }
    bodys.push(html);

    if (javascript) {
        bodys.push(`<script type="text/javascript">(function(){${javascript}})()</script>`);
    }

    return bodys.join("\n");
}


/**
 * @description: 创建liquid文件
 * @param {*}
 * @return {*}
 */
function createLiquid() {
    const tmpContent = JSON.parse(fs.readFileSync(devPath("/index.json"), "utf-8"));
    const pages = Object.keys(tmpContent.page);

    const iconContent = fs.readFileSync(devPath("/style/icon.js"), "utf-8").replace(/module\.exports/g, "const iconObject");
    vm.runInThisContext(iconContent);
    // const buildRoot

    // createTemplateStyle();
    //

    pages.forEach((page) => {
        tmpContent.page[page].forEach((fileName) => {
            const fileDir = `/view/${page}/${fileName}`;

            const liquidDir =  buildPath(`/${page}/${fileName}.liquid`);

            if (!fileName) {
                console.log("错误路径", fileDir);
                return false;
            }

            if (fileName.indexOf("icon_") !== -1) {
                writeFile(`${liquidDir}`, iconObject[fileName] || "");
                return;
            }

            const jsonContent = JSON.parse(fs.readFileSync(devPath(`${fileDir}/index.json`), "utf-8"));
            const htmlContent = fs.readFileSync(devPath(`${fileDir}/index.html`), "utf-8");
            const styleContent = fs.readFileSync(devPath(`${fileDir}/index.scss`), "utf-8");
            const jsContent = fs.readFileSync(devPath(`${fileDir}/index.js`), "utf-8");

            if (page === "snippets") {
                styleContent && (styleFileContent += `\n/** ${fileName} style start **/\n${styleContent}\n/** ${fileName} style end **/\n`);
                jsContent && (javascriptFileContent += jsContent);
                writeFile(`${liquidDir}`, htmlContent);
                return;
            }

            if (page === "sections") {
                let cssContent = "";
                if (styleContent) {
                    cssContent = nodeSass.renderSync({
                        data: styleContent
                    }).css;
                }

                blocksSetting[fileName] = jsonContent.schema;

                writeFile(`${liquidDir}`, createLiquidBody(htmlContent, cssContent, jsContent, jsonContent));
                return;
            }

            // if (page === "snippets") {
            //     styleContent && (styleFileContent += `\n/** ${fileName} style start **/\n${styleContent}\n/** ${fileName} style end **/\n`);
            //     jsContent && (javascriptFileContent += jsContent);
            //     writeFile(`${liquidDir}`, htmlContent);
            //     return;
            // }
        });
    });

    createTemplateStyle(tmpContent);

    createTemplateLayout(tmpContent)
}


/**
 * @description: 创建模版配置文件
 * @param {*}
 * @return {*}
 */
function createSettingDataSchema() {
  
  writeFile(buildPath(`/config/settings_data.json`), JSON.stringify(settingsData));

  writeFile(buildPath(`/config/settings_schema.json`), JSON.stringify(settingsScheme));

  console.log('打包成功');
}

// 询问框
function queryInputTemplateName(name){
    readline.question(name, templateName => {
        if(templateName === "yes" || templateName === "y"){
            getDefaultBlock();

            createLiquid();
        
            getblock();
        
            getPage();
        
            getGlobal();
        
            createSettingDataSchema();

            readline.close()
            return
        }
        if(templateName === "no"){
            readline.close()
            return
        }

        queryInputTemplateName('输入错误重新输入')
    })

}

exports.build = function () {
    queryInputTemplateName(`当前打包模版：${root}\n当前打包目录：${buildRoot}\n确认请输入（yes/y）;取消no`)
}

